// pages/settlement/settlement.js
import mode from '../../utils/mode.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    post:{
      real_name:'',
      id_card:'',
      mobile:'',
      user_id:'',
    },
    couponCanNum:0,
    sureUser:false,   //是否通过实名认证
    showAbord:false,  //提示登记实名认证
    isAbroad:0,     //是否包含有境外仓产品
    is_test: 0,
    testGood: {},
    testGoodId: '',
    orders_type: 3,//3普通订单   1积分商品订单   2积分优惠券订单
    user_id: '',
    address: [],
    choseAddress: null,
    addressType: true,
    addressId: '',
    show: false,
    selectCoupon: '',
    order: null,
    good_ids: '',
    is_cart: 0,
    order_coupon: '',
    coupon_price: '0.00',
    totalPrice: '0.00',
    generalOffer: '0.00',
    integralNumber: 1,
    goods_id: '',
    goods_info: '',
    couponList: [],
    userInfo: {},
    zhekou: 0,
    pageFlage: false,
    coupon_id: null,
    jifenFlag: false,  //积分商品模式，
    test_goods: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function ({ goods_info, is_cart = 0, addressId = '', orders_type = 3, goods_id, number = 1, coupon_id, test_goods = '', testGoodId, is_test,isAbroad }) {
    var uinfo = wx.getStorageSync('uinfo')
    this.setData({
      is_test,
      testGoodId,
      orders_type,
      goods_id,
      integralNumber: number,
      user_id: uinfo.user.id,
      userInfo: uinfo,
      zhekou: uinfo.user.consumption_discount,
      goods_info: goods_info ? JSON.parse(goods_info) : '',
      is_cart,
      coupon_id,
      test_goods,
      addressId,
      isAbroad:isAbroad?isAbroad:0
    })
    //获取地址列表
    await this.getAddress()
    //试用装订单
    if (testGoodId) {
      this.getGoodInfo()
    }
    //积分订单
    if (goods_id) {
      this.integralGoodsDetail()
    }
    // 普通订单
    if (coupon_id) {
      if(is_cart>0){
        this.confirmOrders(coupon_id, true)
      }else{
        this.confirmOrders(coupon_id, false)
      }
      
    } else if (goods_info && !coupon_id) {
      // 兑换券订单
      this.confirmOrders()
    }
    if (addressId) {
      this.setData({
        addressId: addressId
      })
    }
  },

  toUseCoupon(){  //选择不用优惠券
    let list = this.data.couponList
    let isNow = ''
    for(var i = 0; i < list.length; i++) { 
      if(list[i].flag >0) { 
        isNow = i;
        break; 
      } 
    } 
    let is = this.data.selectCoupon
    let now = is=='-1'?isNow:'-1'
    let order = this.data.order
    order.coupon_price = 0
    this.setData({
      order:order,
      selectCoupon: now,
      coupon_id:'',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    if (this.data.addressId) {
      wx.showLoading({ mask: true })
      await this.getAddress()
      //试用装订单
      if (this.data.testGoodId) {
        this.getGoodInfo()
        return
      }
      if (this.data.goods_id) {
        this.integralGoodsDetail()
      } else {
        this.confirmOrders(this.data.coupon_id || '', false)
      }
    }
  },
  async getGoodInfo () {
    let that = this
    wx.showLoading()
    await wx.$api.goodsGetInfo({
        goods_id: that.data.testGoodId
      }).then(res=>{
        if (res.code == 1) {
          that.setData({
            testGood: res.data,
            pageFlage: true,
          })
        } else {
          wx.showToast({
            title: res.msg,
          })
        }
    })
    wx.hideLoading()
  },
  inputUser(e){
    let info = this.data.post
    info.real_name = e.detail.value+""
    this.setData({
      post:info
    })
  },
  inputIdcard(e){
    let info = this.data.post
    info.id_card = e.detail.value+""
    this.setData({
      post:info
    })
  },
  async toSureUser(){
    let that =this
    let { user_id, post,userInfo } = this.data
    if(!post.real_name){
      wx.showToast({
        title: '请先填写姓名',
        icon:'none'
      })
      return
    }else if(!post.id_card){
      wx.showToast({
        title: '请先填写身份证号',
        icon:'none'
      })
      return
    }
    this.setData({
      showAbord:false
    })
    // post.mobile = userInfo.user.mobile
    // post.user_id = user_id||userInfo.user.id
    wx.showLoading({
      title: '实名认证中',
    })
    await wx.$api.authentication({
        real_name:post.real_name,
        id_card:post.id_card,
        mobile:userInfo.user.mobile,
        user_id:user_id||userInfo.user.id,
      }).then(res=>{
        if (res.code == 1) {
          that.getUserInfo(user_id)
          wx.hideLoading()
          wx.showToast({
            title: '认证成功！',
          })
          that.setData({
            sureUser:true
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
    })
    wx.hideLoading()
  },
  getUserInfo (userid) {
    let that = this
    var uinfo = wx.getStorageSync('uinfo')
    mode.getUserInfo(userid).then(item => {
        uinfo.user = item.data
        wx.setStorage({ key: 'uinfo', data: uinfo })
        let userInfo = that.data.userInfo
        userInfo.user = item.data
        that.setData({
          userInfo: userInfo
        })
    })
},
  async integralGoodsDetail () {
    wx.showLoading()
    let { code, data } = await mode.integralGoodsDetail({
      orders_type: this.data.orders_type,
      id: this.data.goods_id
    })
    wx.hideLoading()
    if (code == 1) {
      let { freight } = this.data.userInfo.user
      freight = freight > 0 ? parseFloat(freight).toFixed(2) : 0.01
      this.setData({
        order: data,
        jifenFlag: true,
        pageFlage: true,
        'userInfo.user.freight': freight,
        //totalPrice: data.goods_integral + '积分',
        goods_info: [{ goods_id: data.goods_id, number: this.data.integralNumber || 1 }]
      })
    }
  },
  async redeem () {//积分兑换
    let type = ['', 'integral_good_id', 'integral_coupon_id']
    let { user_id, integralNumber, orders_type, order, goods_id, choseAddress } = this.data
    if (!choseAddress || !choseAddress.id) return wx.showToast({ title: '请选择收货地址！', icon: 'none' })
    wx.showLoading({ title: '兑换中...' })
    let { code, data, msg } = await mode.createIntegralOrder({
      user_id,
      number: integralNumber,
      [type[orders_type]]: order.id,
      address_id: orders_type == 1 ? choseAddress.id : undefined,
      notes: '',
      orders_type
    })
    wx.hideLoading()
    if (code == 1) {
      wx.showToast({ title: '兑换成功!', icon: 'none', mask: true })
      setTimeout(() => {
        app.goUrl(`/pages/orderInfo/orderInfo?isConfirm=1&orders_type=2&order_id=${data.orders_id}`)
      }, 1500)
    } else wx.showToast({ title: msg, icon: 'none' })
  },
  async getCoupon () {
    let { code, data } = await mode.getCoupon({
      user_id: this.data.user_id,
      good_ids: this.data.good_ids
    })
    if (code) {
      let { coupon_id, generalOffer, order: { disparity_price, total_price, vip_price }, userInfo: { user: { freight } } } = this.data
      let price = total_price - vip_price  //vip折扣后的商品价格
      let result = null
      //如果有兑换券存在的话  判断兑换券是否对商品可用
      let { good_ids = '' } = this.data
      let ids = good_ids.split(',')
      let canNum = 0

      Array.isArray(data) && data.forEach((x,i) => {
        // x.flag = x.coupon_use_condition_price <= price
        // if (x.coupon_type == 3) x.flag = ids.includes(x.coupon_exchange_goods + '')
        if (x.order_coupon_user_id == coupon_id){
          result = x
          this.setData({
            selectCoupon:i
          })
        } 
        if(x.flag>0) canNum ++
        if(x.stop_time){
          let m = x.stop_time.substring(0,10)||''
          x.showEndTime = m.replace(/-/g,".")  //"·"
        }
      })
      this.setData({
        couponCanNum:canNum,
        couponList: data,
      })
      if (result) {
        this.setData({
          generalOffer: total_price,
          coupon_price: total_price,
          totalPrice: parseFloat(freight) <= 0 ? 0.01 : parseFloat(freight).toFixed(2),
          order_coupon: result
        })
      }
    } else {
      wx.showToast({
        title: '优惠券获取失败！',
        icon: 'error'
      })
    }

  },
  async confirmOrders (id = '', first = true,is=0) {
    wx.showLoading()
    let { code, data,msg } = await mode.confirmOrders({
      goods_info: JSON.stringify(this.data.goods_info),
      user_id: this.data.user_id,
      order_coupon_id: id,
      address_id: this.data.choseAddress ? this.data.choseAddress.id : ''
    })
    if(code=='10005'){
      // wx.hideLoading()
      // wx.showToast({
      //   title: msg,
      //   icon:'none'
      // })
      if(is<1){
        this.setData({
          coupon_id:''
        })
        this.confirmOrders('',true,1)
      }else{
        setTimeout(() => {
          app.backPage()
        }, 1500)
      }
    }else if(code==1){
      let good_ids = []
      let { zhekou, coupon_id } = this.data
      data.goods.forEach(v => {
        good_ids.push(v.id)
        if (zhekou <= 10 && zhekou > 0){
          v.price = (v.retail_price * (zhekou / 10)).toFixed(2)
        }else{
          v.price = v.retail_price
        }
      })
      data && Object.keys(data).forEach(x => {
        if (typeof data[x] != 'object'&&x!='order_coupon_id'&&x!='order_coupon_name') {
          data[x] = parseFloat(data[x]).toFixed(2)
        }
      })
      // if(data.full_minus_price&&data.full_minus_price.msg){
      //   let text = data.full_minus_price.msg
      //   let arr = []
      //   arr = text.split("，")
      //   if(arr[1]) data.full_minus_price.nextmsg = arr[1]
      // }
      // data.coupon_price = parseFloat(data.coupon_price).toFixed(2)
      this.setData({
        totalPrice: data.sale_price || "0.01",
        generalOffer: data.vip_price || '0.00',
        order: data,
        good_ids: good_ids.join(','),
      })
      if (first) this.getCoupon()
      setTimeout(() => {
        wx.hideLoading()
        this.setData({
          pageFlage: true
        })
      }, 50)
    }else{
      wx.hideLoading()
      wx.showToast({
        title: msg,
        icon:'none'
      })
      setTimeout(() => {
        app.backPage()
      }, 1500)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  async getAddress () { //获取收货地址
    let { code, data } = await mode.getAddress({
      id: this.data.user_id
    })
    let addressId = this.data.addressId
    if (code) {
      let address = data.find(v => {
        if (addressId) {
          return v.id == addressId
        } else return v.is_default == 1
      })
      if(address&&address.address){
        address.showAddress = address.address.replace(/,/g,"    ")
      }
      this.setData({
        choseAddress: address || ""
      })
      if (address) this.phoneStyle()
    }
  },
  phoneStyle () {
    console.log('规划环境规划环境');
    if (this.data.choseAddress) {
      let address = this.data.choseAddress
      let reg = /^[1]([3-9])[0-9]{9}$/
      let phone = address.phone||address.mobile
      if (phone) {
        let str1 = phone.substr(0,3)
        let str2 = phone.substr(7,4)
        address.mobile = str1+'****'+str2
        this.setData({
          choseAddress: address
        })
      }
    }
  },
  calculateTotal () {

    console.log('价格计算', this.data.coupon_price)
    let { sale_price, vip_price, freight } = this.data.order
    let price = Number.parseFloat(sale_price) - this.data.coupon_price + Number.parseFloat(freight)
    let generalOffer = Number.parseFloat(vip_price) + Number.parseFloat(this.data.coupon_price)


    if (!price || price <= 0) price = '0.00'
    this.setData({
      totalPrice: price ? Number(price).toFixed(2) : 0.00,
      generalOffer,
    })
  },
  async toGetTest () {//领取试用装
    let { user_id, testGoodId, choseAddress } = this.data
    if (!choseAddress || !choseAddress.id) return wx.showToast({ title: '请选择收货地址！', icon: 'none' })
    wx.showLoading()
    let { code, data, msg } = await mode.creatTestOrder({
      goods_id: testGoodId,
      user_id,
      address_id: choseAddress.id
    })
    if (code == 1) {
      app.goUrl(`/pages/orderInfo/orderInfo?isTest=1&isConfirm=1&order_id=${data.order_id}&order_number=${data.order_number}&order_real_pay_price=${data.order_real_pay_price || '0.00'}`)
      // wx.showToast({ title: '领取成功！', icon: 'success' })
      // setTimeout(() => {
      //   wx.navigateBack()
      // }, 1000);
    } else wx.showToast({ title: msg, icon: 'none' })
  },
  onCloseSure(){
    this.setData({
      showAbord:false
    })
  },
  async createOrders () {//创建订单
    let { userInfo,sureUser,isAbroad,user_id, choseAddress, order_coupon, is_cart, goods_info, coupon_id } = this.data
    if (!choseAddress || !choseAddress.id) return wx.showToast({ title: '请选择收货地址！', icon: 'none' })
    if(!sureUser&&isAbroad>0&&!userInfo.user.idcard){
      this.setData({
        showAbord:true
      })
      return
    }
    wx.showLoading()
    let { code, data, msg } = await mode.createOrders({
      goods_info: JSON.stringify(goods_info),
      user_id,
      address_id: choseAddress.id,
      order_coupon_id: coupon_id ? coupon_id : order_coupon ? order_coupon.order_coupon_user_id : '',
      freight: '0',//暂时不处理
      is_cart,
    })
    wx.showLoading()
    if (code == 1) {
      app.goUrl(`/pages/orderInfo/orderInfo?isConfirm=1&order_id=${data.order_id}&order_number=${data.order_number}&order_real_pay_price=${data.order_real_pay_price}`)
    } else wx.showToast({ title: msg, icon: 'none' })
  },
  handleClickAddress () {
    let that = this
    if (this.data.choseAddress) {
      wx.navigateTo({
        url: '../address/address?addressType=false&addressId=' + that.data.choseAddress.id,
      })
    } else {
      wx.navigateTo({
        url: '../address/address?addressType=true',
      })
    }

  },
  handleClickOpenCoupon () {
    if(this.data.order.coupon_price>0&&this.data.couponList.length<1){
      return
    }else{
      this.setData({
        show: true,
      })
    }
    
  },
  onClose () {
    this.setData({
      show: false
    })
  },
  // onChange (e) {
  //   const {
  //     name
  //   } = e.currentTarget.dataset
  //   name = name>-1? name:'-1'
  //   this.setData({
  //     selectCoupon: name,
  //   })
  // },
  // 优惠券选择
  handleSeleted () {
    let { selectCoupon, couponList, order: { sale_price, vip_price, disparity_price, freight, jiage, youhui, total_price }, totalPrice, zhekou } = this.data
    let val = selectCoupon>-1?couponList[selectCoupon]:''
    if (val&&selectCoupon>-1) {
      // let total = freight <= 0 ? 0.01 : freight
      // let price = (total_price - 0).toFixed(2)
      // //现金券
      // console.log(`%c>_> =>`, 'color:#ff7b54;font-size:16px;', vip_price + val.coupon_price, total_price, freight)
      // if ((parseFloat(vip_price) + parseFloat(val.coupon_price) < total_price) && val.coupon_type == 2) {
      //   total = (total_price - vip_price - val.coupon_price + parseFloat(freight)).toFixed(2)
      //   price = (parseFloat(vip_price) + parseFloat(val.coupon_price)).toFixed(2)
      // }
      // // 折扣券
      // if (val.coupon_type == 1) {
      //   total_price = total_price - vip_price
      //   total = (total_price * (val.coupon_discount / 10) + parseFloat(freight)).toFixed(2)
      //   let price1 = (total_price - total_price * (val.coupon_discount / 10) + parseFloat(vip_price)).toFixed(2)
      //   price = price1 > total_price ? price : price1
      // }
      this.confirmOrders(val.order_coupon_user_id, false)
      this.setData({
        order_coupon: val,
        coupon_id: val.order_coupon_user_id || ''
      })

    } else {
      this.confirmOrders('', false)
      this.setData({
        //totalPrice: parseFloat(sale_price).toFixed(2),
        //generalOffer: vip_price,
        order_coupon: null,
        //coupon_price: '0.00'
      })
    }
    this.onClose()
    // this.calculateTotal()
  },
  handleclick (e) {
    const { name, flag } = e.currentTarget.dataset
    if (flag>0) {
      let { selectCoupon } = this.data
      let now = name
      if(selectCoupon === name){
        now = '-1'
        this.setData({
          coupon_id: ''
        })
      }
      this.setData({
        selectCoupon: now
      })
    } else {
      // wx.showToast({
      //   title:''
      // })
    }
  },
  goPay () {
    let that = this
    let { order } = this.data
    let arr = []
    wx.login({
      success: function (res) {
        mode.getOpenid(res.code).then(item => {
          mode.goPay(item.data, order.sale_price).then(item => {
            var newObj = JSON.parse(item.data)
            wx.requestPayment({
              nonceStr: newObj.nonceStr,
              package: newObj.package,
              paySign: newObj.paySign,
              timeStamp: newObj.timeStamp,
              signType: 'MD5',
              success (res) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail (res) {
                console.log(res)
                wx.showToast({
                  title: '支付失败',
                  icon: 'error',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    })
  },
})